package com.augmentum.oes.dao.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.augmentum.oes.dao.BaseDao;
import com.augmentum.oes.dao.ExamDao;
import com.augmentum.oes.model.Exam;
import com.augmentum.oes.model.Pagination;
import com.augmentum.oes.model.Question;
import com.augmentum.oes.util.JDBCUtil;

import org.springframework.jdbc.core.RowMapper;

public class ExamDaoImpl extends BaseDao implements ExamDao {

    @Override
    public int addExam(Exam exam) {
        return saveAll(exam);
    }

    @Override
    public List<Exam> queryExam() {
        String sql = "SELECT * FROM exam";
        List<Exam> list = jdbcTemplate.query(sql, new ExamRowMapper());
        return list;
    }

    @Override
    public Exam findById(int id) {
        String sql = "SELECT * FROM exam WHERE id=?";
        return jdbcTemplate.queryForObject(sql, Exam.class);
    }

    @Override
    public void update(Exam exam) {

    }

    @Override
    public void setConnection(int id1, int id2) {
        String sql = "INSERT INTO exam_question(exam_id, bak_id) VALUES (?, ?)";
        jdbcTemplate.update(sql, id1, id2);
    }

    @Override
    public void setToBak(Question question) {
        String sql = "INSERT INTO question_bak(question_content, answer_a, answer_b, answer_c, answer_d, correct_answer) VALUES (?,?,?,?,?,?)";
        save(sql, question);
    }

    @Override
    public List<Exam> examPage(Pagination<Exam> page) {
        String order;
        int orderIndex = page.getOrder();
        switch (orderIndex) {
        case 1:
            order = "id";
            break;
        case 2:
            order = "id DESC";
            break;
        default:
            order = "id";
            break;
        }
        String sql = "SELECT * FROM exam WHERE exam_name LIKE '%"
                + page.getFuzzyWord() + "%' OR id LIKE '%" + page.getFuzzyWord() + "%' ORDER BY "+order+" LIMIT " + page.getOffset() + ","
                + page.getPageSize();
        return jdbcTemplate.query(sql, new ExamRowMapper());
    }

    @Override
    public int getExamCount(String fuzzyTrans) {
        String sql = "SELECT COUNT(id) FROM exam WHERE exam_name LIKE CONCAT('%', ?,'%') OR id LIKE CONCAT('%', ?,'%')";
        return jdbcTemplate.queryForInt(sql);
    }

    class ExamRowMapper implements RowMapper<Exam> {
        @Override
        public Exam mapRow(ResultSet rs, int arg1) throws SQLException {
            Exam exam = new Exam();
            JDBCUtil.toBean(exam, rs);
            return exam;
        }
    }

}
